package com.hjqjl.common_lib.base;

import android.app.Activity;

import java.util.HashSet;
import java.util.Set;

/**
 * 关闭所有activity用的，用System.exit（0）退不全
 * 然后在每个Activity的onCreate()方法中添加下面代码：
 * ActivityCollector.getInstance().addActivity(this);
 * 在需要结束所有Activity的时候调用exit方法：
 * ActivityCollector.getInstance().exit();
 */
public class ActivityCollector {
    private Set<Activity> activityList = new HashSet<>();
    private static ActivityCollector instance;

    private ActivityCollector() {// 单例模式中获取唯一的MyApplication实例
    }

    public static ActivityCollector getInstance() {
        if (null == instance) {
            instance = new ActivityCollector();
        }
        return instance;
    }

    /**
     * 添加Activity到管理
     */
    public void addActivity(Activity activity) {
        if (activityList == null) {
            activityList = new HashSet<>();
        }
        activityList.add(activity);
    }

    /**
     * 从管理器移除Activity，一般在onDestroy移除，防止强引用内存泄漏
     */
    public void removeActivity(Activity activity) {
        if (activityList != null) {
            activityList.remove(activity);
        }
    }

    /**
     * 关闭所有Activity
     */
    public void finishAllActivity() {
        for (Activity activity : activityList) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /**
     * 退出应用程序
     */
    public void appExit() {
        try {
            finishAllActivity();
            // 杀死该应用进程
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}